package org.fitweb.fixture.timing;

import junit.framework.TestCase;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimedExecutorTest extends TestCase {
    public void testTimedExecutorThrowsTimeoutExceptionIfProcessTakesTooLong() throws Exception {
        try {
            TimedExecutor.<Integer>waitFor(1, TimeUnit.SECONDS).on(new SomeCallable(1500));
            fail();
        } catch(TimeoutException e) {
             // Expected
        }
    }

    public void testTimedExecutorStopsWaitingAsSoonAsAResultIsObtained() throws Exception {
        long start = System.currentTimeMillis();

        org.fitweb.fixture.timing.TimedExecutor.<Integer>waitFor(2, TimeUnit.SECONDS).on(new SomeCallable(1));

        long finish = System.currentTimeMillis();
        assertTrue(finish - start < 1000);
    }

    private static class SomeCallable implements Callable<Integer> {
        private int millisToSleep;

        private SomeCallable(int millisToSleep) {
            this.millisToSleep = millisToSleep;
        }

        public Integer call() throws Exception {
            Thread.sleep(millisToSleep);
            return 7;
        }
    }
}